﻿/*
 * Created by SharpDevelop.
 * User: Alice
 * Date: 19.03.2012
 * Time: 06:30
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections;
using System.Timers;

namespace monoServer
{
	/// <summary>
	/// Description of Cron.
	/// </summary>
	public class Cron
	{
		public string cronJobName;
		public Hashtable cronJobList;
		
		public Cron()
		{
			this.cronJobList = new Hashtable();
		}
		
		public Cron(String name)
		{
			this.cronJobName = name;
		}
		
		/*
		public Cron()
		{
			this.cronJobList = new Hashtable();
		}
		*/
		public void addJob(String name, ElapsedEventHandler eeh, int seconds)
		{
			if(seconds <= 0)
				throw new Exception("Cron-Server.addJob - Timer <= 0");
			
			if(name.Equals(String.Empty))
				throw new Exception("Cron-Server.addJob - No Jobname given!");
			try
			{
				Timer tmp = new Timer(seconds*1000);
				tmp.Elapsed += eeh;
				this.cronJobList.Add(name,tmp);	
			} catch(Exception ex) {
				throw new Exception(name + " - " + ex.Message);
			}
		}
		
		public void startJob(String name)
		{
			if(name.Equals(String.Empty))
				throw new Exception("Cron-Server.startJob - No Jobname given");
			
			if(this.cronJobList.ContainsKey(name))
				((Timer)this.cronJobList[name]).Enabled = true;
			else
				throw new Exception("Cron-Server.startJob - The given Jobname doesn't exists in the cronJobList");
			
		}
		
		public void stopJob(String name)
		{
			if(name.Equals(String.Empty))
				throw new Exception("Cron-Server.stopJob - No Jobname given");
			
			if(this.cronJobList.ContainsKey(name))
				((Timer)this.cronJobList[name]).Enabled = false;
			else
				throw new Exception("Cron-Server.stopJob - The given Jobname doesn't exists in the cronJobList");
		}
		
		public void deleteJob(String name)
		{
			if(name.Equals(String.Empty))
				throw new Exception("Cron-Server.deleteJob - No Jobname given");
			
			if(this.cronJobList.ContainsKey(name))
				this.cronJobList.Remove(name);
			else
				throw new Exception("Cron-Server.deleteJob - The given Jobname doesn't exists in the cronJobList");
		}
		
		public void startAllJobs()
		{
			foreach(DictionaryEntry de in this.cronJobList)
			{
				this.startJob((String)de.Key);
			}
		}
		
		public void stopAllJobs()
		{
			foreach(DictionaryEntry de in this.cronJobList)
			{
				this.stopJob((String)de.Key);
			}
		}
	}
}
